import mproj from 'mproj'
import utils from '../utils'
import Dataset from '../dataset'
import {AlbersUSA} from './index.js'
import Common from '../common.js'
import Geom from './index.js'

const projectionAliases = {
  robinson: '+proj=robin +datum=WGS84',
  webmercator: '+proj=merc +a=6378137 +b=6378137',
  wgs84: '+proj=longlat +datum=WGS84',
  // albersusa: new AlbersUSA() // with default parameters
}
function crsToPrj(P) {
  let wkt = null
  try {
    wkt = mproj.internal.wkt_from_proj4(P)
  } catch(e) {
    // console.log(e)
  }
  return wkt
}
function getProjDefn(str) {
  let defn = null
  if (looksLikeProj4String(str)) {
    defn = str
  } else if (str in mproj.internal.pj_list) {
    defn = '+proj=' + str
  } else if (str in projectionAliases) {
    defn = projectionAliases[str]  // defn is a function
  } else {
    defn = Geom.parseCustomProjection(str)
  }
  if (!defn) {
    // stop("Unknown projection definition:", str)
    utils.error(`Unknown projection definition: ${str}`)
  }
  return defn
}
function looksLikeProj4String(str) {
  return /^(\+[^ ]+ *)+$/.test(str)
}
function getCRS(str) {
  const defn = getProjDefn(str)  // defn is a string or a Proj object
  let P
  if (!utils.isString(defn)) {
    P = defn
  } else {
    try {
      P = mproj.pj_init(defn)
    } catch(e) {
      // stop('Unable to use projection', defn, '(' + e.message + ')')
      utils.error(`Unable to use projection${defn}(${e.message})`)
    }
  }
  return P || null
}
function getDatasetCRS(dataset) {
  const info = dataset.info || {}
  let P = info.crs
  if (!P && info.prj) {
    P = parsePrj(info.prj)
  }
  if (!P && Common.probablyDecimalDegreeBounds(Dataset.getDatasetBounds(dataset))) {
    // use wgs84 for probable latlong datasets with unknown datums
    P = getCRS('wgs84')
  }
  return P
}
function isLatLngCRS(P) {
  return P && P.is_latlong || false
}
function translatePrj(str) {
  let proj4 = null
  try {
    proj4 = mproj.internal.wkt_to_proj4(str)
  } catch(e) {
    // stop('Unusable .prj file (' + e.message + ')')
    utils.error(`Unusable .prj file ${e.message}`)
  }
  return proj4
}
// Convert contents of a .prj file to a projection object
function parsePrj(str) {
  return getCRS(translatePrj(str))
}
export default {
  crsToPrj,
  getCRS,
  getDatasetCRS,
  isLatLngCRS,
}